package com.example.demo.msg.aio.client;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CountDownLatch;

public class ReadHandle implements CompletionHandler<Integer,ByteBuffer> {

    private AsynchronousSocketChannel channel;

    private CountDownLatch latch;

    public ReadHandle(AsynchronousSocketChannel channel,CountDownLatch latch) {
        this.channel = channel;
        this.latch = latch;
    }

    @Override
    public void completed(Integer integer, ByteBuffer buffer) {
        buffer.flip();
        byte[] bytes = new byte[buffer.remaining()];
        buffer.get(bytes);


        try {
            String expression = new String(bytes, "UTF-8");
            System.out.println("客户端收到消息: " + expression);


        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();


        }
    }

    @Override
    public void failed(Throwable throwable, ByteBuffer buffer) {

        System.err.println("数据读取失败...");

        try {
            channel.close();
            latch.countDown();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}